#!/usr/bin/env sh
current_dir=$(cd $(dirname $0) && pwd)
source_dir=$current_dir/libedit-20221030-3.1
install_dir=$current_dir/install
build_dir=$current_dir/build

function usage {
    echo "usage: $0 -n/--ncurses-install dir"
}

if [ $# -ne 2 ]; then
    echo "error: no required option"
    usage
    exit 1
fi

if [ $1 = "-n" ] || [ $1 = "--ncurses-install" ]; then
    ncurses_install_dir=$2
else
    echo "error: unknown option: $1"
    usage
    exit 1
fi

ncurses_include_dir=$ncurses_install_dir/include
ncurses_lib_dir=$ncurses_install_dir/lib

# Do a clean build
rm -rf $build_dir && rm -rf $install_dir && \
    mkdir -p $install_dir && mkdir -p $build_dir && \
    cd $build_dir

mac_sdk_root=$(xcrun --show-sdk-path)

CC=/System/Volumes/Data/data/llvm/builds/HsxB3o3v/0/rus-os-team/compilers/aosp/platform/manifest/prebuilts/clang/ohos/darwin-x86_64/clang-15.0.4/bin/clang
CXX=/System/Volumes/Data/data/llvm/builds/HsxB3o3v/0/rus-os-team/compilers/aosp/platform/manifest/prebuilts/clang/ohos/darwin-x86_64/clang-15.0.4/bin/clang++

export CC=${CC=clang}
export CXX=${CXX=clang++}

lld_ldflags="-fuse-ld=lld"
ncurses_ldflags="-L$ncurses_lib_dir"
pic_cflags="-fPIC"
ncurses_cflags="-I$ncurses_include_dir"

export CFLAGS="$CFLAGS $ncurses_cflags $pic_cflags -isysroot$mac_sdk_root -Wl,-syslibroot,$mac_sdk_root $lld_ldflags"
export CXXFLAGS="$CXXFLAGS $CFLAGS"
export LDFLAGS="$LDFLAGS $ncurses_ldflags"
export CPPFLAGS="-isysroot$mac_sdk_root"
export CXXPPFLAGS="$CPPFLAGS"

$source_dir/configure \
    --prefix=$install_dir

make -j$(nproc --all) install | tee build.log
